package com.utp.freemarker.controller;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

/**
 * @author Arnold Yand
 * @since Mar 22, 20172:00:53 PM
 * @summary com.utp.freemarker.controller.ResourcesController.java
 */
@Controller
public class ResourcesController {

    private final Map<String, String> contentType = new HashMap<String, String>();

    @RequestMapping("/resource")
    public void getResource(String path, HttpServletRequest request, HttpServletResponse response) throws IOException {
        try {
            if (null != path) {
                // response.setContentType(contentType.getOrDefault(path.substring(path.lastIndexOf(".")), "text/html"));
                response.setContentType(contentType.get(path.substring(path.lastIndexOf("."))));
                
                PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
                Resource resource = resolver.getResource("com/utp/freemarker/resources/" + path);

                InputStream is = resource.getInputStream();
                ServletOutputStream out = response.getOutputStream();
                int read = 0;
                byte[] buffer = new byte[1024 * 8];
                while ((read = is.read(buffer)) != -1) {
                    out.write(buffer, 0, read);
                }
                is.close();
                out.flush();
                out.close();
            }
        } catch (FileNotFoundException e) {
            // resource file does not exist
        }
    }

    public ResourcesController() {
        contentType.put(".js", "text/js");
        contentType.put(".css", "text/css");
        contentType.put(".gif", "image/gif");
        contentType.put(".jpg", "image/jpeg");
        contentType.put(".jpeg", "image/jpeg");
        contentType.put(".png", "image/png");
        contentType.put("default", "text/html");
    }
}
